<template>
  <div class="full-screen-div">
    <div class="login-container">
      <div class="login-title">登录</div>
      <el-form :model="loginForm" @submit="mobileLogin">
        <el-form-item label="用户名" label-position="left">
          <el-input v-model="loginForm.empId"></el-input>
        </el-form-item>
        <el-form-item label="密码" label-position="left">
          <el-input type="password" v-model="loginForm.password"></el-input>
        </el-form-item>
        <el-form-item class="login-button-item">
          <el-button type="primary" native-type="submit" class="login-button">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import { ref } from 'vue';
import { login } from '../api/user.js'
import { createUserStore } from '../state/user.js'
import { getSessionStorageObj } from '../utils/common.js'
import router from '../router/index'
import { getUserOfInfo } from '../api/user.js'

const loginForm = ref({
  empId: '',
  password: ''
});

//得到全局数据
const userStore = createUserStore()
userStore.userInfo

const mobileLogin = async (e) => {  // 添加事件参数
  e?.preventDefault();  // 防止默认表单提交行为
  console.log('登录信息:', loginForm.value);

  if (!loginForm.value.empId || !loginForm.value.password) {
    ElMessage.warning("账号或密码不能为空");
    return;
  }

  try {
    userStore.resetUserInfo();  // 重置用户信息
    const loginRes = await login(loginForm.value);
    console.log("登录响应:", loginRes);

    if (loginRes.flag) {
      // 存储 token
      const expiresIn = 604800;
      sessionStorage.setItem("token", loginRes.result);
      sessionStorage.setItem("token_expires_at", Date.now() + expiresIn * 1000);

      // 获取用户信息
      const userRes = await getUserOfInfo(loginForm.value.empId);
      console.log("用户信息响应:", userRes);

      if (userRes.flag) {
        // 更新用户信息并持久化存储
        userStore.setUserInfo(userRes.result);
        // 路由跳转
        await router.push('/betch');
        ElMessage.success('登录成功');
      } else {
        ElMessage.error('获取用户信息失败！' + userRes.reason);
      }
    } else {
      ElMessage.error('登录失败！' + loginRes.reason);
    }
  } catch (error) {
    ElMessage.error('登录失败：' + error.message);
  }
};
</script>

<style scoped>
.full-screen-div {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #E1EFFF;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-container {
  width: 300px;
  padding: 20px;
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.login-title {
  font-size: 24px;
  margin-bottom: 20px;
  color: #333;
  text-align: center;
}

.el-form-item {
  margin-bottom: 20px;
}

.login-button-item {
  display: flex;
  justify-content: center;
  /* 使用flex布局使按钮居中 */
}

.login-button {
  width: 100%;
  /* 使按钮宽度与表单项宽度一致 */
}
</style>